package com.xiaoran.springcloud.controller;


import com.xiaoran.springcloud.entitis.CommonResult;
import com.xiaoran.springcloud.entitis.Payment;
import com.xiaoran.springcloud.lb.LoadBalanced;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;


@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
   private LoadBalanced loadBalanced;

    @GetMapping("/consumer/payment/create")
    public CommonResult create(Payment payment){
    //    return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
        return restTemplate.postForEntity(PAYMENT_URL+"/payment/create",payment,CommonResult.class).getBody();
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") int id){
        /*List<ServiceInstance> instances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");//获取当前名字下的所有提供者
        if(instances==null || instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance=loadBalanced.instance(instances);
        URI uri=serviceInstance.getUri();
        */
       return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);

      /*  ResponseEntity<CommonResult> entity= restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
       if (entity.getStatusCode().is2xxSuccessful()){
           return entity.getBody();
       }else{
           return new CommonResult<>(444,"操作失败");
       }
       */

    }

    @GetMapping("/consumer/payment/lb")
    public String getPaymentlb(){
        //获取到我们CLOUD-PAYMENT-SERVICE名字下的所有提供者
        List<ServiceInstance> instances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances==null || instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance=loadBalanced.instance(instances);
        URI uri=serviceInstance.getUri();
        log.info("*****我的URI地址是：{}",uri);
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }


    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin(){
        String reslut=restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin",String.class);
        return reslut;
    }
}
